package gonet

import (
	"crypto/tls"
	"net/smtp"
)

// SmtpInfo SMTP server configuration.
type SmtpInfo struct {
	Host     string `json:"host" xml:"host"`
	Port     string `json:"port" xml:"port"`
	From     string `json:"from" xml:"from"`
	Password string `json:"password" xml:"password"`
}

// Send 发送邮件
func Send(to []string, subject string, body string, info *SmtpInfo) error {
	msg := []byte("To: " + info.From + "\r\n" +
		"Subject: " + subject + "\r\n" +
		"\r\n" + body + "\r\n")

	// Setup authentication information.
	auth := smtp.PlainAuth("", info.From, info.Password, info.Host)

	// Connect to the SMTP Server with TLS.
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         info.Host,
	}
	conn, err := tls.Dial("tcp", info.Host+":"+info.Port, tlsConfig)
	if err != nil {
		return err
	}

	client, err := smtp.NewClient(conn, info.Host)
	if err != nil {
		return err
	}

	// Authenticate.
	if err = client.Auth(auth); err != nil {
		return err
	}

	// Set the sender and recipient first.
	if err = client.Mail(info.From); err != nil {
		return err
	}

	for _, addr := range to {
		if err = client.Rcpt(addr); err != nil {
			return err
		}
	}

	// Send the email body.
	w, err := client.Data()
	if err != nil {
		return err
	}

	_, err = w.Write(msg)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}

	// Quit and close the connection.
	err = client.Quit()
	if err != nil {
		return err
	}
	return nil
}
